package GUI;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class UpdateXml 
{ 
	String userName;
	String password;
	
	
	
	public UpdateXml(String userName, String password) 
	{
		this.userName = userName;
		this.password = password;
	}



	public void update()
	{
		String fileName = "../"+"Tag Manager"+"/src/hibernate.cfg.xml";
		File file = new File(fileName);
		
		//Create instance of DocumentBuilderFactory
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		//Get the DocumentBuilder
		DocumentBuilder docBuilder;
		try 
		{
			docBuilder = factory.newDocumentBuilder();
			//Parsing XML Document
			Document doc = docBuilder.parse(file);
			Element root = doc.getDocumentElement();
			NodeList nodes = root.getChildNodes();
			nodes = nodes.item(1).getChildNodes();

			//changing the user name in the xml
			nodes.item(5).getChildNodes().item(0).setNodeValue(userName);
			//changing the password in the xml
			nodes.item(7).getChildNodes().item(0).setNodeValue(password);
			
			//setting up a transformer
			TransformerFactory transfac = TransformerFactory.newInstance();
			Transformer trans = transfac.newTransformer();

			//generating string from xml tree
			StringWriter sw = new StringWriter();
			StreamResult result = new StreamResult(sw);
			DOMSource source = new DOMSource(doc);
			trans.transform(source, result);
			String xmlString1 = sw.toString();
			String xmlString = xmlString1.substring(0,54);
			xmlString = xmlString + "\n<!DOCTYPE hibernate-configuration PUBLIC    \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\">\n\t";
			xmlString = xmlString + xmlString1.substring(54);
			//Saving the XML content to File
			OutputStream f0;
			byte buf[] = xmlString.getBytes();
			f0 = new FileOutputStream("../"+"Tag Manager"+"/src/hibernate.cfg.xml");
			for(int i=0; i<buf.length; i++) 
			{
				f0.write(buf[i]);
			}
			f0.close();
			buf = null;

		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}


}
